// pages/ideal/ideal.js
const util = require("../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    show:false,
    fileList: [
    ],
    uid:null
  },

  onPost(){
    this.setData({show:true})
    setTimeout(()=>{
      this.setData({show:false})
      wx.reLaunch({
        url: '/pages/index/index'
      });
    },1000);
  },

  afterRead(event) {
    const that = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      filePath: file.url,
      header:{"Content-Type":"multipart/form-data"},
      url: 'http://127.0.0.1:3527/upfile',
      name: 'imgfile',
      formData: { dir:"post" },
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = that.data;
        const result = JSON.parse(res.data);
        let path = 'http://localhost:3527/images/post/'+result.data;
        fileList.push({ ...file, url: path });
        that.setData({ fileList });
      },
    });
  },

  handleDelete(event) {
    const index = event.detail.index;
    const fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({ fileList: [...fileList] });
  },

  onInputChange(e) {
    this.setData({
      content: e.detail.value
    });
  },

  onSubmit(event){
    const content = this.data.content;
    if (content === '') {
      util.showErrorToast("请输入文字");
      return;
    }
    console.log('用户输入的内容:', content);
    console.log(this.data.fileList);
    const { fileList } = this.data;
    let insertid = null;
    let that = this;
    wx.request({
      url:'http://127.0.0.1:3527/posts/add',
      method:'POST',
      data:{
        "user_id":wx.getStorageSync('uid'),
        "content":content
      },
      success(res){
        insertid = res.data.data.insertId;
        console.log("插入ID:",insertid);
        fileList.forEach((file, index) => {
          console.log(`第${index + 1}张图片:`, file.url);
          wx.request({
            url:'http://127.0.0.1:3527/posts/addimg',
            method:'POST',
            data:{
              "post_id":insertid,
              "url":file.url
            },
          });
        });
        that.setData({show:true});
        that.onPost();
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let uid = wx.getStorageSync('uid');
    this.setData({
      uid:uid
    })
    // if (!uid) wx.switchTab({
    //   url: '/pages/me/me',
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let uid = wx.getStorageSync('uid');
    this.setData({
      uid:uid
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})